import os
from distutils.command.config import config

from . import BaseView
from tkinter import Frame, Text, Scrollbar, Tk


class TextView(Frame, BaseView):
    def __init__(self, parent, delegetor):
        super().__init__(parent)
        BaseView.__init__(self, delegetor)
        self.text_plate = Text(self, font=('宋体', 12), undo=True, state='disabled')
        self.scrollbal = Scrollbar(self, orient='vertical')
        self.scrollbal.pack(side='right', fill='y')
        self.text_plate.pack(side='right', fill='both')
        self.scrollbal['command'] = self.text_plate.yview
        self.text_plate['yscrollcommand'] = self.scrollbal.set

        self.text_plate.pack(fill='both', expand=True)

        self.path = None
        self.text_plate.bind('<Double-Button-3>', self.open_by_others)
        self.text_plate.bind("<Control-MouseWheel>", self.zoom)

    def open(self, path):
        super().open(path)
        self.path = path
        self.text_plate['state'] = 'normal'
        self.text_plate.delete("1.0", "end")
        with open(path, 'r', encoding="utf-8") as f:
            text = f.read()
        self.text_plate.insert("1.0", text)
        self.text_plate['state'] = 'disabled'

    def close(self):
        return super().close()

    def file_extension(self):
        return ".txt"

    def set_config(self, config: dict):
        super().set_config(config)
        self.text_plate['font'] = config['font']

    def get_basic_config(self):
        return {
            "font": ('宋体', 12),
            "exec": "notepad"
        }

    def zoom(self, event):
        delta = event.delta
        font_name, font_size = self.text_plate['font'].split(" ")
        font_size = int(font_size)
        if delta > 0:
            font_size += 1
        else:
            font_size -= 1
        self.text_plate['font'] = (font_name, font_size)
        self.config['font'] = (font_name, font_size)



if __name__ == '__main__':
    root = Tk()
    txt = TextView(root)
    txt.pack()
    txt.open(r"D:\app\art-note\art-note\ArtNote.py")
    root.mainloop()
